﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Wicresoft.SMS.Data;
using System.Security.Principal;

namespace Wicresoft.SMS.Web
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class CustomAuthoriseAttribute : AuthorizeAttribute
    {
        public static IUserRoleService _service;
        public AuthoriseFlag Flag { get; set; }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
                throw new ArgumentNullException("httpContext");
            if (_service == null)
                _service = DependencyInjectFacotry.CreateUserRoleService();
            //if no _service always consider true
            if (_service == null)
                return true;

            IPrincipal user = httpContext.User;
            if (!user.Identity.IsAuthenticated)
            {
                return false;
            }

            WebConfigProvider wcp = new WebConfigProvider();
            IUserService us = new UserService(wcp);

            var temp = us.GetUserItemByCIL(user.Identity.Name);
            if (temp.IsActive == 3)
                return false;

            long[] values = _service.GetRolesValueForUser(user.Identity.Name);
            if (values == null)
                return false;
            long value = 0;
            foreach (long v in values)
                value |= v;
            if ((value & (long)Flag) != (long)Flag)
                return false;

            return true;

        }

        private int CheckAuthorize(HttpContextBase httpContext)
        {
            if (httpContext == null)
                throw new ArgumentNullException("httpContext");
            if (_service == null)
                _service = DependencyInjectFacotry.CreateUserRoleService();
            //if no _service always consider true
            if (_service == null)
                return 0;

            IPrincipal user = httpContext.User;
            if (!user.Identity.IsAuthenticated)
            {
                return 1;
            }

            WebConfigProvider wcp = new WebConfigProvider();
            IUserService us = new UserService(wcp);

            var temp = us.GetUserItemByCIL(user.Identity.Name);
            if (temp.IsActive <= 3)//|| temp.IsActive == 2 || temp.IsActive == 0)
                return 2;
            //else if (temp.IsActive == 1)
            //    return 1;

            long[] values = _service.GetRolesValueForUser(user.Identity.Name);
            if (values == null)
                return 1;
            long value = 0;
            foreach (long v in values)
                value |= v;
            if ((value & (long)Flag) != (long)Flag)
                return 1;

            return 0;
        }


        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            //if (this.AuthorizeCore(filterContext.HttpContext))
            //{
            //    //filterContext.Result = new RedirectResult("/home");
            //    HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
            //    cache.SetProxyMaxAge(new TimeSpan(0L));
            //    cache.AddValidationCallback(new HttpCacheValidateHandler(this.CacheValidateHandler), null);
            //}
            //else
            //{
            //    //this.HandleUnauthorizedRequest(filterContext);
            //    filterContext.Result = new RedirectResult("/home");
            //}

            int flag = this.CheckAuthorize(filterContext.HttpContext);

            if (flag == 0)
            {
                HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
                cache.SetProxyMaxAge(new TimeSpan(0L));
                cache.AddValidationCallback(new HttpCacheValidateHandler(this.CacheValidateHandler), null);
            }
            else if (flag == 1)
            {
                this.HandleUnauthorizedRequest(filterContext);
            }
            else
            {
                filterContext.Result = new RedirectResult("/home");
            }

        }

        private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus)
        {
            validationStatus = this.OnCacheAuthorization(new HttpContextWrapper(context));
        }



    }

    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class CustomIsActiveAttribute : AuthorizeAttribute
    {
        public static IUserRoleService _service;
        public AuthoriseFlag Flag { get; set; }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
                throw new ArgumentNullException("httpContext");
            if (_service == null)
                _service = DependencyInjectFacotry.CreateUserRoleService();
            //if no _service always consider true
            if (_service == null)
                return true;

            IPrincipal user = httpContext.User;
            if (!user.Identity.IsAuthenticated)
            {
                return false;
            }

            WebConfigProvider wcp = new WebConfigProvider();
            IUserService us = new UserService(wcp);

            var temp = us.GetUserItemByCIL(user.Identity.Name);
            if (temp == null)
                return false;

            long[] values = _service.GetRolesValueForUser(user.Identity.Name);
            if (values == null)
                return false;
            long value = 0;
            foreach (long v in values)
                value |= v;
            if ((value & (long)Flag) != (long)Flag)
                return false;

            return true;

        }

        //public override void OnAuthorization(AuthorizationContext filterContext)
        //{
        //    if (filterContext == null)
        //    {
        //        throw new ArgumentNullException("filterContext");
        //    }
        //    if (this.AuthorizeCore(filterContext.HttpContext))
        //    {
        //        //filterContext.Result = new RedirectResult("/home");
        //        HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
        //        cache.SetProxyMaxAge(new TimeSpan(0L));
        //        cache.AddValidationCallback(new HttpCacheValidateHandler(this.CacheValidateHandler), null);
        //    }
        //    else
        //    {
        //        this.HandleUnauthorizedRequest(filterContext);
        //        // filterContext.Result = new RedirectResult("/home");
        //    }
        //}

        //private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus)
        //{
        //    validationStatus = this.OnCacheAuthorization(new HttpContextWrapper(context));
        //}



    }
}